
#include <Trade/Trade.mqh>

input int    AutoCloseMinutes = 30;    // 平仓间隔（分钟）
input double MinProfit = 3;         // 最小盈利金额（账户货币）

CTrade Trade;
datetime LastCloseTime;

int OnInit()
{
    EventSetTimer(1);
    LastCloseTime = 0;
    return(INIT_SUCCEEDED);
}

void OnTimer()
{
   datetime currentTime = TimeTradeServer();

   if (currentTime - LastCloseTime >= AutoCloseMinutes * 60)
   {
      CloseProfitablePositions();
      LastCloseTime = currentTime;
      Print("自动平仓执行时间：", TimeToString(currentTime));
   }
}

//+------------------------------------------------------------------+
//| 平仓盈利持仓函数                                                 |
//+------------------------------------------------------------------+
void CloseProfitablePositions()
{
   for(int i = PositionsTotal()-1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);
      if(PositionSelectByTicket(ticket))
      {
         string symbol = PositionGetString(POSITION_SYMBOL);
        //  if(symbol == _Symbol)
         {
            double profit = PositionGetDouble(POSITION_PROFIT);
            if(profit >= MinProfit)  // 添加最小盈利条件
            {
               Trade.PositionClose(ticket);
               Print("已平仓盈利订单：#", ticket, 
                     " 利润：", DoubleToString(profit, 2),
                     " 达到最小盈利要求：", DoubleToString(MinProfit, 2));
            }
         }
      }
   }
}